import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/http.dart';
import 'package:flutter/material.dart';

import '../../utils/eventBus.dart';
import '../../utils/toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  // 接收userInfo参数
  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 需要定义状态变量 userInfo 引发视图更新
  Map userInfo = {
    "id": "",
    "avatar": null,
    "nickName": null,
  };

  //昵称控制器
  final TextEditingController nikNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 更新状态变量userInfo
    setState(() {
      userInfo = widget.userInfo;
      // 显示昵称
      nikNameController.text = userInfo['nickName'] ?? '';
    });
  }

  // 修改昵称
  void editNickName() async {
    // 1.获取昵称
    String nikName = nikNameController.text;
    // 判断昵称是否为空
    if (nikName.isEmpty) {
      return ToastUtil.showError('昵称不能为空');
    }
    // 限制昵称长度
    if (nikName.length > 10) {
      return ToastUtil.showError('昵称长度不能超过10个字符');
    }
    // 2.发送请求
    try {
      var res = await MyHttp.put('/userInfo', data: {"nickName": nikName});
      // print(res);{code: 10000, message: 操作成功, data: {id: 6827386278137856}}
      if (res['code'] != 10000) {
        // 修改失败
        return ToastUtil.showError('修改昵称失败,$res["code"]: $res["message"]');
      }
      // 显示成功提示
      ToastUtil.showSuccess('$res');
    } catch (e) {
      ToastUtil.showError('修改昵称失败');
    }
  }

// 从相机或相册中选择图片 --展示半模态
  void showBottomSheet() async {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  trailing: Icon(Icons.arrow_forward_ios_rounded),
                  onTap: () async {
                    // 调用相机
                    ImagePicker picker = ImagePicker();
                    final XFile? photo =
                        await picker.pickImage(source: ImageSource.camera);
                    if (photo != null) {
                      print('photo.path:$photo.path');
                      uploadAvatar(photo.path);
                    }
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.image),
                  title: const Text('相册'),
                  trailing: Icon(Icons.arrow_forward_ios_rounded),
                  onTap: () async {
                    // 调用相机
                    ImagePicker picker = ImagePicker();
                    final XFile? image =
                        await picker.pickImage(source: ImageSource.gallery);
                    if (image != null) {
                      print('image.path:$image.path');
                      uploadAvatar(image.path);
                    }
                  },
                )
              ]));
        });
  }

  /// 上传图片
  uploadAvatar(String imagePath) async {
    try {
      // 1. 包装一个FormData对象
      FormData fd = FormData.fromMap(
          {"file": await MultipartFile.fromFile(imagePath), "type": "avatar"});
      ToastUtil.showSuccess('$fd');
      // 2. 调用上传接口
      var res = await MyHttp.post('/upload', {"file": fd});
      if (res['code'] != 10000) {
        print(res);
        return ToastUtil.showError('上传图片失败');
      }
      setState(() {
        userInfo['avatar'] = res['data']['url'];
        ToastUtil.showSuccess('上传图片成功');
      });
    } catch (e) {
      ToastUtil.showError('上传图片失败$e');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        // 左侧返回按钮
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            // 返回前，发出刷新事件通知
            eventBus.fire(BackMineEvent());
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    // 添加从本地上传图片的功能
                    GestureDetector(
                        onTap: () {
                          // 展示半模态
                          showBottomSheet();
                        },
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child: userInfo['avatar'] != null
                                ? Image.network(
                                    userInfo['avatar'],
                                  )
                                : Image.asset('assets/images/avatar_1.jpg',
                                    width: 30, height: 30))),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  // 关联控制器
                  controller: nikNameController,
                  decoration: const InputDecoration(
                      hintText: '请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                  // 当输入内容结束时，触发事件
                  onEditingComplete: () {
                    // 修改昵称
                    editNickName();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
